/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Statistic.Dao.js
 * @path:   js-src/album/
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-04-25
 */
qui(
    function (require, exports, module) {
        Statistic.Dao = $.extend({}, EpgWeb.Dao, {
            cfgName: {
                LogType: "vod_log"
            },
            getChannelType: function (handler) {
                var ajaxOptions = {
                    type: "post",
                    url: EpgWeb.urlConfig.redirect,
                    dataType: "json",
                    data: {"request": JSON.stringify({url: Statistic.Constant.thirdUrl_channel_type, type: "get", params: {size: 100}, needCookie: true}), timeSign: new Date().getTime()},
                    success: function (data) {
                        var formatData = [];
                        $.each(data.data, function (i, element) {
                            formatData.push({id: element.id, label: element.name, value: element.name})
                        })
                        handler(formatData);
                        console.log("renderPanel happen");
                    },
                    error: function (data) {
                        console.log("error happen");
                    }
                };
                $.ajax(ajaxOptions)
            },

            getExportData: function (data, callback) {
                var options = {
                    url: Statistic.urlConfig.sdGetUrl,
                    dataType: 'json',
                    data: data,
                    type: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                Ancestor.Dao.ajax(options, '/sd');
            },
            getExportDataAll: function (params, handler) {
                var daoSelf = this;
                params.pageNo = 1;
                handler.lockHandler();
                var queryComponent = {
                    params: params,
                    dataArr: [],
                    phase: 0,
                    hasFlushNum: 0,
                    query: function () {
                        var self = this;
                        daoSelf.getExportData(params, function (data) {
                            if (data == null) {
                                EpgWeb.Plugin.showTips({content: "请求失败", type: "error"  })
                                handler.phaseHandler(self.dataArr);
                                handler.unlockHandler();
                            } else {
                                self.dataArr = self.dataArr.concat(data.data.result);
                                self.phase++;
                                handler.phaseHandler(self.dataArr, "phase" + self.phase);
                                console.log("self.phase:" + self.phase);
                                self.hasFlushNum += self.dataArr.length;
                                self.dataArr = [];
                                if (self.hasFlushNum < data.data.totalCount) {
                                    self.params["pageNo"] = params.pageNo + 1;
                                    console.log("params.pageNo:" + self.params["pageNo"]);
                                    self.query();
                                } else {
                                    handler.unlockHandler();
                                }
                            }
                        })
                    }
                };
                queryComponent.query();
            },
            postSync: function (postUrl, postData, handler, sync) {
                var async = sync == null ? true : sync != true;
                var options = {
                    cache: false,
                    async: async,
                    type: "post",
                    dataType: "json",
                    url: postUrl,
                    data: postData,
                    success: function (res) {
                        handler.doSuc(res);
                    },
                    error: function () {
                        handler.doError();
                    }
                }
                Ancestor.Dao.ajax(options);
            },
            submitLogEntity: function (data, callback) {
                var url = Statistic.urlConfig.submitVodLogUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(data)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/vod/saveLog");
            },
            submitEpisodeLogEntity: function (data, callback) {
                var url = Statistic.urlConfig.submitEpisodeLogUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(data)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/vod/saveEpisodeLog");
            },
            logType: function () {
                return this.getDataByName(this.cfgName.LogType);
            },

            makeOptionsCheckLegoVideoData: function (programId) {
                var self = this;
                return {
                    type: "get",
                    url: Statistic.Constant.thirdUrl_query_videos,
                    dataType: "json",
                    data: {filter: {EQL_entityId: "" + programId}, page: {pageSize: 2, pageNo: 1, orderBy: "createTime", order: "desc"}},
                    beforeQuery: function (options, resultData) {
                        console.log("beforeQuery " + JSON.stringify(resultData));
                        var newOptions = self.transToProxyOptions(options, {Sign: "#f93Uc31K24()_@"})
                        return newOptions;
                    },
                    judge: function (data) {
                        if (data != null && data.code == "A00000") {
                            if (data.data.result.length == 1) {
                                var isReTranscode = Statistic.Util.isAvailableForReTranscode(data.data.result[0]);
                                if (!isReTranscode) {
                                    EpgWeb.Plugin.showTips({type: "error", content: "当前节目不支持重新发布"});
                                }
                                return isReTranscode;
                            }
                            return false;
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: Statistic.Constant.thirdUrl_query_videos + " 接口请求失败:" + JSON.stringify(data)});
                            return false;
                        }
                    }
                }
            },

            makeOptionsGetEpisodeLogList: function (programId, typeValues, descrLikes) {
                var paramsObj = {EQL_programId: "" + programId, INI_type: typeValues}
                if (descrLikes != null) {
                    paramsObj["LIKES_description"] = descrLikes
                }
                var sendData = { pageSize: 20, pageNo: 1, paramsObj: JSON.stringify(paramsObj), timeSign: Date.now() };
                var options = {
                    url: Statistic.urlConfig.getEpisodeLogUrl,
                    dataType: 'json',
                    data: sendData,
                    type: 'post',
                    judge: function (data) {
                        if (data == null) {
                            EpgWeb.Plugin.showTips({type: "error", content: "/api/vod/episodeLogList 无响应"});
                        } else if (data.code == "A00000") {
                            return true;
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: data.msg});
                        }
                        return false;
                    }
                }
                return this.appendAuthUrl(options, '/vod/episodeLogList');
            },
            makeOptionsGNotifyLegoRemake: function (needResultKey, overrideData) {
                return  {
                    type: "post",
                    url: EpgWeb.urlConfig.redirect,
                    dataType: "json",
                    needResult: needResultKey,
                    checkNeedResult: function (resultData) {
                        var dataArr = resultData.data.result;
                        if (dataArr != null && dataArr.length > 0) {
                            var type = dataArr[0].type;
                            return type == Statistic.Config.VOD_LOG_TYPE.delayWrapDataToLego
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: "缺少延时发送lego 日志数据"});
                        }
                        return false;
                    },
                    beforeQuery: function (options, resultData) {
                        console.log("beforeQuery " + JSON.stringify(resultData));
                        var dataArr = resultData.data.result;
                        var selectElement = dataArr[0].descr;
                        var programId = dataArr[0].programId;
                        var type = dataArr[0].type;
                        // type == Statistic.Config.VOD_LOG_TYPE.delayWrapDataToLego
                        var elementArr = selectElement.split("|");
                        var retVal = elementArr.shift();
                        var oldUrl = elementArr.shift().substring(4);
                        var sendData = JSON.parse(elementArr.join("|"));
                        if (overrideData != null) {
                           // sendData = $.extend({}, sendData, overrideData);
                            sendData =   Statistic.Util.decodeSendLegoData( sendData ,overrideData )
                        }
                        var newOptions = $.extend({}, options, {
                            data: sendData,
                            success: function (data) {
                                options.success(data);
                                Statistic.Util.episodeLogSubmit(programId, Statistic.Config.VOD_LOG_TYPE.sendWrapDataToLego_suc, sendData, data, "fromUrl:" + oldUrl);
                            }, error: function (XMLHttpRequest, status) {
                                options.error(null);
                                Statistic.Util.episodeLogSubmit(programId, Statistic.Config.VOD_LOG_TYPE.sendWrapDataToLego_fail, sendData, { type: "error reqeust", status: status }, "fromUrl:" + oldUrl);
                            }
                        });
                        return newOptions;
                    },
                    judge: function (data) {
                        if (data != null && data.code == 'A00000') {
                            if (data.data.programId != null && data.data.programId > 0) {
                                return true;
                            } else {
                                EpgWeb.Plugin.showTips({type: "error", content: "lego节目ID 返回为空"});
                            }
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: "lego接口无效返回值"});
                        }
                        return false;
                    }
                }
            },
            makeOptionsDadianPublish: function (needResultkey, overrideData) {
                return  {
                    type: "post",
                    url: EpgWeb.urlConfig.redirect,
                    dataType: "json",
                    needResult: needResultkey,
                    checkNeedResult: function (resultData) {
                        var dataArr = resultData.data.result;
                        return dataArr != null && dataArr.length > 0;
                    },
                    beforeQuery: function (options, resultData) {
                        console.log("beforeQuery " + JSON.stringify(resultData));
                        var dataArr = resultData.data.result;
                        var selectElement = dataArr[0].descr;
                        var channelId = dataArr[0].channelId;
                        var programId = dataArr[0].programId;
                        var elementArr = selectElement.split("|");
                        var retVal = elementArr.shift();
                        var oldUrl = elementArr.shift().substring(4);
                        var sendUrl = oldUrl.split("/dot")[0] + "/dot/publish";
                        var params = {programId: programId, from_client: true};
                        if (overrideData != null) {
                            params = $.extend({}, params, overrideData);
                        }
                        var newOptions = $.extend({}, options, {
                            url: sendUrl,
                            data: params,
                            success: function (data) {
                                options.success(data);
                                Statistic.Util.episodeLogSubmit(programId, Statistic.Config.VOD_LOG_TYPE.notifyWrapPublish, params, data, "fromUrl:" + sendUrl);
                            }, error: function (XMLHttpRequest, status) {
                                options.error(null);
                                Statistic.Util.episodeLogSubmit(programId, Statistic.Config.VOD_LOG_TYPE.notifyWrapPublish, params, null, "fromUrl:" + sendUrl);
                            }
                        });
                        return newOptions;
                    },
                    judge: function (data) {
                        if (data == null) {
                            EpgWeb.Plugin.showTips({type: "error", content: "/dot/publish 接口请求失败!"});
                        } else if (data.error != null && parseInt(data.error) == 0) {
                            EpgWeb.Plugin.showTips({ content: "请求成功"});
                            return true;
                        } else {
                            EpgWeb.Plugin.showTips({ content: "请求失败:" + JSON.stringify(data)});
                        }
                        return false;
                    }
                }
            },
            makeOptionsCheckHasSendLego: function (programId, typeValues, descrLikes) {
                var paramsObj = {EQL_programId: "" + programId, INI_type: typeValues}
                if (descrLikes != null) {
                    paramsObj["LIKES_description"] = descrLikes
                }
                var sendData = { pageSize: 20, pageNo: 1, paramsObj: JSON.stringify(paramsObj), timeSign: Date.now() };
                var options = {
                    url: Statistic.urlConfig.getEpisodeLogUrl,
                    dataType: 'json',
                    data: sendData,
                    type: 'post',
                    judge: function (data) {
                        if (data == null) {
                            EpgWeb.Plugin.showTips({type: "error", content: "/api/vod/episodeLogList 无响应"});
                        } else if (data.code == "A00000") {

                            return true;
                        } else {
                            EpgWeb.Plugin.showTips({type: "error", content: data.msg});
                        }
                        return false;
                    }
                }
                return this.appendAuthUrl(options, '/vod/episodeLogList');
            }
        })

    }
);